<template>
    <div style="flex: 90%; margin-left: 20px">

      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="选日期">
          <el-date-picker style="width:150px"
                  v-model="data.dateTime"
                  type="date"
                  placeholder="Pick a day"
                  size="large"
                  @change="handleDateChange"
              />
        </el-form-item>
        <el-form-item>
          <el-select @change="handleIndustry($event)"  v-model="industryType" placeholder="Select" size="large" class="select">
            <el-option v-for="item in options_industry" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearchByDate">下一天</el-button>
          <el-icon style="margin-left:16px;font-size: 24px;color:#409EFF" @click="flush"><Refresh /></el-icon>
          <el-switch style="margin-left:20px;" v-model="isMinute" @change="on_switch_normal()" active-icon="" inline-prompt active-text="分时" inactive-text=" 日线"/>
          <el-text style="margin-left:16px;">{{ getPlayTime(progress) }}</el-text>
          <!-- 进度条-->
          <el-slider style="width:260px;margin-left:20px;margin-right:20px;" v-model="progress" :min="0" :max="241" @input="onProgressChange" :format-tooltip="formatTooltip"/>

          <el-button-group>
            <el-button :icon="Minus" @click="decrease" />
            <el-button :icon="Plus" @click="increase" />
          </el-button-group>
        </el-form-item>

      </el-form>

      <div style="display: flex;">
        <!--左-->
        <div style="flex:12%;margin-right: 12px;">
          
          <el-table
            v-loading="loading"
            row-key="code"
            :data="tableIndustry"
             class="custom-border"
            @sort-change="handleSortChangeIndustry"
            style="width:238px"
          >
            <el-table-column  label="序号" style="margin-left:6px" :width="56">
                <template #default="scope">
                    <el-text >{{scope.$index + 1}}</el-text>
                </template>
            </el-table-column>

            <el-table-column prop="orderIndex" label="名称" sortable="custom" :width="110" >
                <template #default="scope">
                    <el-text @mouseover="handleMouseOver(scope.row)" :style="{color:getSelectIndustyStyleColor(scope.row.name),fontWeight:getSelectIndustyStyleWight(scope.row.name),fontSize:getSelectIndustyStyleFontSize(scope.row.name)}">{{scope.row.name}}</el-text>
                </template>
            </el-table-column>

            <el-table-column prop="close" label="涨幅" sortable="custom" :width="labWidthChange" >
                <template #default="scope">
                    <el-text @click="onLoadIndustryStock(scope.row.name)" :style="{color:getIncreaseTextColorCkOpenClose(scope.row.close, scope.row.ckTodayClose)}">{{getNowData(scope.row.close)}}</el-text>
                </template>
            </el-table-column>

          </el-table>    

        </div>

        <div style="flex:12%">
          <!--中-->
          <el-table
            v-loading="loading"
            row-key="code"
            :data="tableStock"
            class="custom-border"
            @sort-change="handleSortChange"
            style="width:238px;height:800px;overflow-y:auto;margin-top: 0%;"
          >
            <el-table-column prop="orderIndex" label="序号" :width="55">
                <template #default="scope">
                    <el-text >{{scope.$index + 1}}</el-text>
                </template>
            </el-table-column>

            <el-table-column prop="orderIndex" label="名称" sortable="custom" :width="110" >
                <template #default="scope">
                    <el-text @mouseover="handleMouseOver(scope.row)">{{scope.row.name}}</el-text>
                </template>
            </el-table-column>

            <el-table-column prop="close" label="涨幅" sortable="custom" :width="labWidthChange">
                <template #default="scope">
                    <el-text :style="{color:getIncreaseTextColorCkOpenClose(scope.row.close, scope.row.ckTodayClose)}">{{getNowData(scope.row.close)}}</el-text>
                </template>
            </el-table-column>

          </el-table>

        </div>

        <div style="flex:76%">
          <!--右-->
          <div width="800" style="width:50%;height:100%;margin-top: 0%;">  
            <TimeChartReplay :progress="progress"/>
            <KLineReplay />
          </div>  
        </div>

      </div>
    </div>
  </template>
    
  <script lang="ts" setup>
  import { onMounted, ref , defineEmits} from "vue";
  import type { TableColumnCtx, TableInstance } from "element-plus";
  import { reactive } from "vue";
  import axios from "axios";
  import { countdownEmits, ElMessage, ElMessageBox, ElNotification } from "element-plus";
  import ClipboardJS from 'clipboard';
  import { createStore } from 'vuex';
  import type { Action } from 'element-plus';
  import {Check,Delete,Edit,Message,Search, Star, CloseBold,Close,QuestionFilled
          } from '@element-plus/icons-vue';
  import KLineReplay from "./base/KLineReplayComponent.vue";
  import TimeChartReplay from "./base/TimeChartReplayComponent.vue";
  import { Minus, Plus } from '@element-plus/icons-vue'

  // ElNotification({
  //   title: '情绪周期',
  //   message: "<p style='color:#008888'>指数</p>",
  //   duration: 0,
  //   dangerouslyUseHTMLString: true,
  //   showClose:false,
  // })
  const progress = ref(0)
  const isChangeAmountVisible = ref(false);
  const customColor = ref('#409eff')
  const localImagePath = ref('file:///F:/typora/1.png');
  const labWidth = ref(70);
  const labWidthChange = ref(80);
  const data = reactive({
    code: "",
    name: "",
    dateTime: "",
    playTime: "09:30",
    note:"",
    id:0,
    isSelected:true,
  });
  const isSelectTopOrClickIndustry = ref(true)
  const isMinute = ref(true)
  const stressScore = ref(1);
  const industryType = ref("短线");
  const thsIndustryName = ref("");
  const isAsc = ref(false);
  const options_industry = [
  { value: '股票' },
  { value: 'A股指数' },
                    { value: '同花顺行业板块' },
                    { value: '同花顺概念' },
                    { value: '同花顺概念第2天' },
                    { value: '同花顺热门板块' },
                    { value: 'ETF' },
                    { value: 'ETF第2天' },
                    { value: '情绪' },
                    { value: '短线' },
                    { value: '第2天入场' },
                    { value: '第3天出场' },
                    { value: '龙虎榜' },
                    { value: '龙虎榜第2天' },
                    { value: '东方财富热榜' },
                    { value: '同花顺热榜' },
                    { value: '涨停容量榜' },
                    { value: '负反馈榜' },
                    { value: '今日涨停板' },  
                    { value: '涨停板第2天' },  
                    { value: '涨停板第3天' },  
                    { value: '中概港股' },
                    { value: '港股' },
                    { value: '美股' },
                    { value: '中概美股' },
                    { value: '全球指数' },
                  ];
  // 刷新
  const flush = () => {
    onLoadIndustry();
    if (isSelectTopOrClickIndustry.value) {
      onLoadStock();
    } else {
      onLoadIndustryStock(thsIndustryName.value);
    }
  }                
  const onLoadStock = () => {
    console.log("submit!");
    var time = data.dateTime;

    if (isMinute.value) {
      time = data.dateTime + " " + data.playTime + ":00"
    }
    const api = "api/plat/stockDayRecord/findPageList/1/100?isMinute=" + isMinute.value + "&isAsc=" + isAsc.value + "&recordDate=" + time + "&strA=" + encodeURIComponent(industryType.value);
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = response.data.data.list;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

  const onLoadIndustry = () => {
    console.log("submit!");
    var time = data.dateTime;
    if (isMinute.value) {
      time = data.dateTime + " " + data.playTime + ":00"
    }
    var strA = "同花顺行业板块";
    const api = "api/plat/stockDayRecord/findPageList/1/100?isMinute=" + isMinute.value + "&isAsc=false&recordDate=" + time + "&strA=" + encodeURIComponent(strA);
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableIndustry.value = response.data.data.list;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

  const onLoadIndustryStock = (industry:string) => {
    console.log("submit!");
    thsIndustryName.value = industry;
    isSelectTopOrClickIndustry.value = false;
    var time = data.dateTime;
    if (isMinute.value) {
      time = data.dateTime + " " + data.playTime + ":00"
    }
    const api = "api/plat/stockDayRecord/findIndustryStock?industryType=" + encodeURIComponent(industry) + "&dayTime=" + time + "&isMinute=" + isMinute.value + "&isAsc=false"
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = response.data.data;
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

  const onLoadScoreBySort = (orderBy: string) => {
    console.log("submit!");
    const api = "api/plat/stockDayRecord/findPageList/1/100?recordDate=" + data.dateTime + "&strA=" + encodeURIComponent(industryType.value);
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        tableStock.value = response.data.data.list;
        var list = response.data.data.list;
        stressScore.value = 0;
        for (var i = 0; i < list.length; i++) {
          stressScore.value = stressScore.value + getStressScore_Yes(list[i]);
          console.log("分数：" + stressScore.value);
        }
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

  const handleIndustry = (value) => {
      industryType.value = value;
      if (value === "A股指数" || value === "同花顺行业板块" ) {
        isChangeAmountVisible.value = true;
      } else {
        isChangeAmountVisible.value = false;
      }
      isSelectTopOrClickIndustry.value = true;
  }

  interface stockDayRecord {
    id: number;
    recordDate:string;
    name: string;
    code: string;

    tip: String;

    bidding: number;
    open: number;
    close: number;
    max: number;
    min: number;
    yesOpen: number;
    yestoday: number;
    
    tomOpen: number;
    tomClose: number;

    continuousNumber: number;
    allNumber: number;
    docId: number;

    importantScore: number;
    stressScore: number;

    note: string;

    ckTodayOpen: number;
    ckTodayClose: number;
    ckTomOpen: number;
    ckTomClose: number;

    ckTodayOpenBoolean: boolean;
    ckTodayCloseBoolean: boolean;
    ckTomOpenBoolean: boolean;
    ckTomCloseBoolean: boolean;

    orderIndex: number;
    intA: number;
    timeList: StockNowTime[];

    amount:number;
    changeAmount: number;
  }

  interface StockNowTime {
    timeRecord: string;
    increase: number;
  }

  interface StockIndicatorOk {
    id: number;
    recordId: number;
    indicator: string;
    condition: string;
    isOk: number;
    data: number;
    type: string;
    note: string;
    mark: string;
  }

  interface StockNowPrice {
    id: number;
    name: string;
    tscode: string;
  }

  interface StockTigger {
    code: string;
    buySailType: number;
    name: string;
    realName: string;
    buyMoney: number;
    percent1: number;
    sailMoney: number;
    percent2: number;
    netMoney: number;
    strA: string;
  }

  const showStressColumn = ref(false);
  const isPlay = ref(true);
  const loading = ref(false);
  const tableStock = ref([]);
  const tableIndustry = ref([]);

  const score_type = [
                { value: '5',label: '5级', },
                { value: '4',label: '4级', },
                { value: '3',label: '3级' },

                { value: '2',label: '2级' },
                { value: '1',label: '1级' },
                { value: '0',label: '0级' },
            ]

  var code = ''
  const index = ref(0);
  onMounted(() => {
        document.title = "同花顺";
        data.dateTime = getToday();
        onLoadIndustry();
        setInterval(() => {
          index.value = index.value + 1;
          if (index.value >= 100) {
            index.value = 0;
          }
        }, 1000);

        const clipboard = new ClipboardJS('.btn-copy', {
          text: () => code
        });
  
        clipboard.on('success', (e) => {
          console.log('Text copied to clipboard');
          e.clearSelection();
        });
  
        clipboard.on('error', (e) => {
          console.error('Failed to copy text: ', e);
        });
   });
  
   const getNegativeScore_str = (row: stockDayRecord) => {
      var xs = getNegativeScore(row);
      if (xs > 0) {
        return '' + xs;
      }
      return ''; 
    }

    const getNegativeScore = (row: stockDayRecord) => {
      var xs = 0.00;  
      if (row.yestoday <= -3 && row.yestoday > -5) {
        xs = 1;
      }
      if (row.yestoday <= -5 && row.yestoday > -8) {
        xs = 3;
      }
      if (row.yestoday <= -8 && row.yestoday > -10.5) {
        xs = 5;
      }
      xs = xs * row.yestoday / 5.00;
      return xs; 
    }

    const getNegativeScore_Yes_str = (row: stockDayRecord) => {
      var xs = getNegativeScore_Yes(row);
      if (xs > 0) {
        return '' + xs;
      }
      return ''; 
    }
    const getNegativeScore_Yes = (row: stockDayRecord) => {
      var importantScore = 5.0;
      var xs = 0.00;  
      if (row.yestoday <= -3 && row.yestoday > -5) {
        xs = 1;
      }
      if (row.yestoday <= -5 && row.yestoday > -8) {
        xs = 3;
      }
      if (row.yestoday <= -8 && row.yestoday > -10.5) {
        xs = 5;
      }
      xs = 0.6 * xs * importantScore / 5.00;// 昨天的乘以60%
      return xs; 
    }

    const getStressScore_Yes_str = (row: stockDayRecord) => {
      var xs = getStressScore_Yes(row);
      if (xs >= 3) {
        return '' + xs;
      }
      return ''; 
    }

    const getStressScore_Yes = (row: stockDayRecord) => {
      var xs = 0.00;  
      if (row.bidding <= 8 && row.bidding > 5) {
        xs = 1;
      }
      if (row.bidding <= 9.90 && row.yestoday > 8) {
        xs = 2;
      }
      if (row.bidding > 9.90) {
        xs = 3;
      }
      xs = xs * row.stressScore / 3.00;// 昨天的乘以60%
      return xs; 
    }

    const getIncreaseBgColor = (row: stockDayRecord) => {
      // if (row.yestoday <= -9.90) {
      //   return 'green'; 
      // } else {
      //   return 'white';
      // }
      return '#000000'
    }

    const getIncreaseTextColor = (value:number) => {

      if (value <= -9.90) {
        return 'green'; 
      } else {
        if (value <= 0 && value > -9.90) {
          return 'green'; 
        } else {
          if (value < 9.90 && value > 0) {
            return '#F56C6C'; 
          } else {
            return 'red';
          }
        }
      }
    
    }

    // 定义emit事件
    const emit = defineEmits(['selectCode']);
    const handleMouseOver =  (row: stockDayRecord) =>{
      // 触发selectCode事件，并传递数据给父组件
      emit('selectCode', { stockCode: row.code, stockName: row.name, stockTime: data.dateTime });
    }

    const getBuySailColor = (strA:string) => {
      if (strA === '买') {
        return '#F56C6C'; 
      } else {
        return '#67C23A'; 
      }
    }

    const getMoneyColor = (money:number) => {
      if (money >= 0) {
        return '#F56C6C'; 
      } else {
        return '#67C23A'; 
      }
    }

    const getMoneyStr = (money:number) => {
      if (money >= 10000 || money <= -10000) {
        return Number(money / 10000).toFixed(2) + "亿"; 
      } else {
        return money + "万"; 
      }
    }

    const getAllDifMoney = (index:number, money:number) => {
      if (index === 0) {
        if (money >= 10000 || money <= -10000) {
          return Number(money / 10000).toFixed(2) + "亿"; 
        } else {
          return money + "万"; 
        }
      } else {
        return ""; 
      }
    }

    const getAllDifMoneyColor = (money:number) => {
      if (money > 0) {
        return '#F56C6C'; 
      } else {
        return '#67C23A'; 
      }
    }

    const getSelectIndustyStyleColor = (name:string) => {
        if (!isSelectTopOrClickIndustry.value && name === thsIndustryName.value) {
            return '#333333';
        }
    }

    const getSelectIndustyStyleFontSize = (name:string) => {
        if (!isSelectTopOrClickIndustry.value && name === thsIndustryName.value) {
            return '16px';
        }
    }


    const getSelectIndustyStyleWight = (name:string) => {
        if (!isSelectTopOrClickIndustry.value && name === thsIndustryName.value) {
            return 'bolder';
        }
    }

    const getIncreaseTextColorCkOpenClose = (value:number, ckOpenClose:number) => {

      if (ckOpenClose === 0) {
        return '#333333'; 
      }

      if (value <= -9.90) {
        return 'green'; 
      } else {
        if (value <= 0 && value > -9.90) {
          return 'green'; 
        } else {
          if (value < 9.90 && value > 0) {
            return '#F56C6C'; 
          } else {
            return 'red';
          }
        }
      }
  }

  const getAmountColor = (value:number) => {
    
    if (value >= 1000000000) {
        return '#800080';
      } else {
        return '#666666';  
      }
  }

  const getChangeAmountColor = (changeAmount:number) => {
    if (changeAmount < 0) {
      return 'green'; 
    } else {
      return 'red';
    }
  }


    const getIncreaseTextColorCkXXXXXXXXX = (row:stockDayRecord,value:number, ckOpenClose:number) => {
      console.log(row.name, value);
      if (ckOpenClose === 0) {
        return '#333333'; 
      }
      
      if (value <= -9.90) {
        return 'green'; 
      } else {
        if (value <= 0 && value > -9.90) {
          return 'green'; 
        } else {
          if (value < 9.90 && value > 0) {
            return '#F56C6C'; 
          } else {
            return 'red';
          }
        }
      }
    
    }

    const getIncreaseData = (increase:number, ckOpenClose:number) => {
        // if (ckOpenClose === 1) {
        //   return increase.toFixed(2) + "%";
        // } else { 
        //   return "--";  
        // }
        return increase.toFixed(2) + "%";
    }

    const getNowData = (increase:number) => {
      return increase.toFixed(2) + "%";
    }

    const getMoneyData = (money:number) => {
      return (money / 100000000).toFixed(2) + "亿"
    }

    const getIncreaseFontWeight_Yes = (row: stockDayRecord) => {
      if (row.yestoday <= -8.0) {
        return 'bold'; 
      } else {
        return 'normal';
      }
    }
   
    const getShortNameType = (row: stockDayRecord) => {
      return "测试"; 
    }
    
    const handleSortChange = ({ column, prop, order })  => {
      console.log('排序字段:', prop);
      console.log('排序顺序:', order); // ascending, descending
      if (industryType.value === "股票" || industryType.value === "同花顺概念" || industryType.value === "ETF") {
        isAsc.value = order === 'ascending';
        onLoadStock();
      } else {
        if (order === 'ascending') {
          tableStock.value.sort((a, b) => b[prop] - a[prop]);
        } else {
          tableStock.value.sort((a, b) => a[prop] - b[prop]);
        }
      }
    }

    const handleSortChangeIndustry = ({ column, prop, order })  => {
      console.log('排序字段:', prop);
      console.log('排序顺序:', order); // ascending, descending
      if (order === 'ascending') {
        tableIndustry.value.sort((a, b) => b[prop] - a[prop]);
      } else {
        tableIndustry.value.sort((a, b) => a[prop] - b[prop]);
      }
    } 

    const on_switch_normal = () => {
      if(isMinute.value) {
        
      } else {
        
      }
    };

    const onProgressChange = (value)  => {
      data.playTime = getPlayTime(value);
     
      flush();
    };


    const increase = ()  => {
      progress.value = progress.value + 1;
      if (progress.value >= 240) {
        progress.value = 0;
      }
      onProgressChange(progress.value);
    };

    const decrease = ()  => {
      progress.value = progress.value - 1;
      if (progress.value < 0) {
        progress.value = 0;
      }
      onProgressChange(progress.value);
    };
    
    const formatTooltip = (value)  => {
      return getPlayTime(value);
    };

    const getPlayTime = (value) => {
      const times = [];
      for (let i = 30; i < 60; i++) {//9:30-9:59
        times.push("09:" + i);
      }
      for (let i = 0; i < 60; i++) {//10:00-10:59
        if (i < 10) {
          times.push("10:0" + i);
        } else {
          times.push("10:" + i);
        }
      }
      for (let i = 0; i <= 30; i++) {//11:00-11:30
        if (i < 10) {
          times.push("11:0" + i);
        } else {
          times.push("11:" + i);
        }
      }
      for (let i = 0; i < 60; i++) {//13:01-13:59
        if (i < 10) {
          times.push("13:0" + i);
        } else {
          times.push("13:" + i);
        }
      }
      for (let i = 0; i < 60; i++) {//14:00-14:59
        if (i < 10) {
          times.push("14:0" + i);
        } else {
          times.push("14:" + i);
        }
      }
      times.push("15:00");//15:00
      console.log("时间长度" + times.length);
      return times[value];
    };

    const handleDateChange = (val) => {
        console.log('选择了新的日期/时间:', val);
        const date = new Date(val)
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
        const day = ('0' + date.getDate()).slice(-2);
        const dayTime = `${year}-${month}-${day}`;
        console.log('选择了新的日期/时间:', dayTime);

        const date1 = new Date(getToday());
        const date2 = new Date(dayTime);

        if (date1 < date2) {
          ElMessage({
            message: "日期不能晚于今天",
            type: "error",
          });
          return;
        }

        data.dateTime = dayTime;
        onLoadStock();
    };

    const getLink  = (row:StockNowPrice) => {
      // 动态生成链接
      return "https://www.iwencai.com/unifiedwap/result?w=" + data.dateTime + encodeURIComponent("同花顺一级行业" + row.name + "所有的涨停股票及成交金额");
    };
    const isLinkShow  = () => {
      // 动态生成链接
      return industryType.value == "同花顺行业板块"
    };
    
    const shouldShowButton = (row: StockIndicatorOk, value) => {
      if (row.isOk == value) {
        return true;
      }
    }

    const shouldShowButtonTigger = (row: stockDayRecord) => {
      if (row.intA === 1) {
        return true;
      } else {
        return false;
      }
    }

    const onUpdate = (params) => {
      console.log("submit!" + params);
     
      axios
        .put("api/plat/stockDayRecord/update", params)
        .then((response) => {
          // console.log(response.status);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    };

    const onUpdateIndicatorOk = (params) => {
      console.log("submit!" + params);
     
      axios
        .put("api/plat/stockIndicatorOk/update", params)
        .then((response) => {
          // console.log(response.status);
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    };
 
  const onAddZhiShuRecord = () => {
      console.log("submit!");
      const api = "api/plat/stockDayRecord/loadZhishuData?dayTime=" + data.dateTime;
      console.log(api) 
      axios
        .get(api)
        .then((response) => {
          
        })
        .catch((error) => {
          console.error("Error fetching data:", error);
        });
    };

    const getToday = () =>  {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
      const day = String(today.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }
  </script>
    
    <style >
    .custom-border {
      border: 0.5px solid #dfe6ec;
      background-color: #000000;
    }
    
    .custom-border th, .custom-border td {
      border: 0.5px solid #dfe6ec;
      background-color: #00000000;
    }

    
    .el-table__body tr:hover > td {
      background-color: #00000000 !important;
    }
    .el-table .el-table__header th {
      color: #999;       /* 字体颜色 */
      font-weight:100; /* 字体粗细 */
      font-size: 13px;   /* 字体大小 */
      background-color: #00000000;
      /* background-color: #f5f7fa; 背景颜色（可选） */
    }

    </style>